const errorTypes = require('../constants/error-types')

const errorHandler = (error, ctx) => {
	let statusCode, message

	switch (error.message) {
		case errorTypes.USERNAME_OR_PASSWORD_IS_REQUIRED:
			statusCode = 400 // bad request
			message = errorTypes.USERNAME_OR_PASSWORD_IS_REQUIRED
			break

		case errorTypes.USER_ALREADY_EXISTS:
			statusCode = 409 // conflict
			message = errorTypes.USER_ALREADY_EXISTS
			break

		case errorTypes.USER_DOES_NOT_EXIST:
			statusCode = 400
			message = errorTypes.USER_DOES_NOT_EXIST
			break

		case errorTypes.PASSWORD_IS_INCORRECT:
			statusCode = 400
			message = errorTypes.PASSWORD_IS_INCORRECT
			break

		case errorTypes.UNAUTHORIZATION:
			statusCode = 401
			message = errorTypes.UNAUTHORIZATION
			break

		case errorTypes.UNPERMISSION:
			statusCode = 401
			message = errorTypes.UNPERMISSION
			break

		default:
			statusCode = 404
			message = 'NOT FOUND'
	}

	ctx.status = statusCode
	ctx.body = message
	
}

module.exports = errorHandler
